<template>
  <h1>学生信息</h1>
  <br />

  <!--加载新增学生自定义控件-->
  <NewStudent />

  <!--table begin  -->
  <a-table :rowKey="recode=>recode.stu_code" :columns="columns" :data-source="dataSource" bordered>
    <!--左侧基本数据表列 begin-->
    <template v-for="col in ['stu_code', 'stu_name', 'stu_gender', 'birthday', 'photo', 'class_name', 'phone_num']" #[col]="{ text, record, index }">
      <div :key="col">
        <a-input v-if="record.editable" style="margin: -5px 0" :value="text" @change="(e) => handleChange(e.target.value, record.key, col)" />
        <template v-else>
          {{ text }}
        </template>
      </div>
    </template>
    <!--左侧基本数据表列 end-->

    <!--右侧操作按钮列 begin-->
    <template #operation="{ text, record, index }">
      <div class="editable-row-operations">
        <span v-if="record.editable">
          <a @click="save(record.key)">保存</a>
          <a-popconfirm title="确定要取消?" @confirm="cancel(record.key)">
            <a>取消</a>
          </a-popconfirm>
        </span>
        <span v-else>
          <a v-bind="editingKey !== '' ? { disabled: 'disabled' } : {}" @click="edit(record.key)"> 编辑 </a>
        </span>

        <a-popconfirm
          v-if="dataSource.length"
          title="Sure to delete?"
          @confirm="onDelete(record.key)"
        >
          <a>Delete</a>
        </a-popconfirm>
      </div>
    </template>
    <!--右侧操作按钮列 end-->
  </a-table>
  <!--table end-->
</template>

<script>
import NewStudent from "../../../components/NewStudent.vue";
import axios from 'axios';
import qs from 'qs';
import { Modal } from 'ant-design-vue';

//var qs = Qs;

const columns = [
  {
    title: "学号",
    dataIndex: "stu_code",
    key: "stu_code",
    //width: "25%",
    slots: { customRender: "stu_code" },
  },
  {
    title: "姓名",
    dataIndex: "stu_name",
    key: "stu_name",
    //width: "15%",
    slots: { customRender: "stu_name" },
  },
  {
    title: "性别",
    dataIndex: "stu_gender",
    key: "stu_gender",
    //width: "40%",
    slots: { customRender: "stu_gender" },
  },
  {
    title: "生日",
    dataIndex: "birthday",
    key: "birthday",
    slots: { customRender: "birthday" },
  },
  {
    title: "照片",
    dataIndex: "photo",
    key: "photo",
    slots: { customRender: "photo" },
  },
  {
    title: "班级",
    dataIndex: "class_name",
    key: "class_name",
    slots: { customRender: "class_name" },
  },
  {
    title: "电话",
    dataIndex: "phone_num",
    key: "phone_num",
    slots: { customRender: "phone_num" },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slots: { customRender: 'operation' },
  },
];

const dataSource = [];
/*
for (let i = 0; i < 100; i++) {
  dataSource.push({
    stu_code: i.toString(),
    stu_name: `Edrward ${i}`,
    stu_gender: "男",
    birthday: "1990 - 01 - 01",
    photo: `London Park no. ${i}`,
    class_name: "软件01",
    phone_num: "13888888888",
  });
}*/
export default {
  name: "StudentList",
  components: {
    NewStudent,
  },
  data() {
    return {
      dataSource,
      columns,
      editingKey: "",
      //rowKey:"stu_code",
    };
  },
  mounted(){
    var __this = this;
    //ajax 访问 api
    //获取所有学生信息
    axios
    /*.post('http://127.0.0.1:8080/student/find_stu_by_name',qs.stringify({
        'stu_name': '张三', // 参数 stuName
    }), {headers:{
        'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    }})*/
    .get('http://127.0.0.1:8080/student/stu_list')
    .then(function(response){
      __this.dataSource=response.data;
      __this.cacheData = __this.dataSource.map(item => ({ ...item }));
    })
    .catch(function (error) { // 请求失败处理
        console.log(error);
    });
    this.cacheData = dataSource.map((item) => ({ ...item }));
    console.log(this.cacheData);
  },
  methods: {
    //编辑时动态获取值
    handleChange(value, key, column) {
      const newData = [...this.dataSource];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    //编辑，更改当前行为编辑状态
    edit(key) {
      const newData = [...this.dataSource];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.dataSource = newData;
      }
    },
    //保存
    save(key) {
      const newData = [...this.dataSource];
      const newCacheData = [...this.cacheData];
      console.log("newCacheData",newCacheData);
      const target = newData.filter((item) => key === item.key)[0];
      console.log("编辑后的新行值：",target);
      const targetCache = newCacheData.filter((item) => key === item.key)[0];
      console.log("targetCache",targetCache);
      
      if (target && targetCache) {
        
        //将更新保存到服务器
        axios
        .post('http://127.0.0.1:8080/student/update_stu_by_code',
               qs.stringify(target)
        )
        /*
        .then(function(response){
          console.log("服务器 response",response);
          delete target.editable;
          this.dataSource = newData;
          Object.assign(targetCache, target);
          this.cacheData = newCacheData;
          //弹出对话框提示已经更新成功
          const modal = Modal.success({
            //title: 'This is a notification message',
            content: '更新成功!',
          });
          consol.log("modal",modal);
          //modal.visible=true;
        })*/
        .then(response=>{
          console.log("服务器 response",response);
          delete target.editable;
          this.dataSource = newData;
          Object.assign(targetCache, target);
          this.cacheData = newCacheData;
          //弹出对话框提示已经更新成功
          Modal.success({
            title: 'Success',
            content: '更新成功!',
          });
          //consol.log("modal",modal);
          //modal.visible=true;
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
      }
      

      this.editingKey = "";
    },
    //取消编辑
    cancel(key) {
      const newData = [...this.dataSource];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = "";
      if (target) {
        Object.assign(target, this.cacheData.filter((item) => key === item.key)[0]);
        delete target.editable;
        this.dataSource = newData;
      }
    },
    //删除当前行
    onDelete(key) {
      //const dataSource = [...this.dataSource];
      //this.dataSource = dataSource.filter(item => item.key !== key);
      console.log("deleteKey",key)
      const newData = [...this.dataSource];
      const target = newData.filter((item) => key === item.key)[0];
      console.log("deletetarget",target)
      if (target) {
        
        //将删除操作执行到服务器
        axios
        .post('http://127.0.0.1:8080/student/delete_one',
               qs.stringify(target)
        )
        .then(response=>{

          //弹出对话框提示已经删除成功
          Modal.success({
            title: 'Success',
            content: '删除成功!',
          });
          //在前端视图中，也删除指定行
          this.dataSource = newData.filter(item => item.stu_code !== target.stu_code);
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
        
      }
    },
  },

};
</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
.editable-add-btn {
  margin-bottom: 8px;
}
.ant-modal-confirm-title{
  color:rgb(82,196,26);
}
</style>
